<template>
	<view class="container">
		<view class="body">
			<view class="module_box">
				<view class="moduletitle">
					{{goodsName}}
				</view>
				<view class="time_box">
					<view class="titles">
						游玩日期
					</view>
					<view class="times_box" show-scrollbar="true" scroll-x="true" scroll-left="120">
						<!-- <scroll-view class="times_box" scroll-x="true"> -->
						<template v-for="(v,i) in timesList" :key="i">
							<view :class="['timesBox',checkTime===v.timer?'checkTime':'']" @click="checkTimeFn(v)">
								<view>{{v.text}}</view>
								<view>{{v.times}}</view>
							</view>
						</template>
					</view>
				</view>
				<view class="price_box">
					<view class="price_text">
						<view class="titles">
							购买数量
						</view>
						<view class="">
							购买须知
						</view>
					</view>
					<view class="price_number">
						<view :class="['btn',num<=1?'':'checks']" @click="editTourist">
							-
						</view>
						<view class="num">
							{{num}}
						</view>
						<view class="btn checks" @click="addTourist">
							+
						</view>
					</view>
				</view>
			</view>
			<view class="module_box">
				<view class="title">
					<view>联系人信息</view>
					<view><uni-icons type="calendar" style="color: orangered;" @click="openSelUser" size="30"></uni-icons></view>
				</view>
				<view class="">
					<!-- {{checkuserList}} -->
					<uni-list-item title="姓名" :rightText="checkuserList.name" ></uni-list-item>
					<uni-list-item title="手机号" :rightText="checkuserList.tel" ></uni-list-item>
					<uni-list-item title="证件号" :rightText="checkuserList.idcard" ></uni-list-item>
					
				</view>
			</view>
			<view class="module_box">
				<view class="title">
					游玩人信息
				</view>
				<view class="user_list">
					<template v-for="(v,i) in userList" :key="i">
						<!-- check_pheuser -->
						<view :class="['user_list_box',v.check==true?'check_pheuser':'']" @click="toChecktourist(i,v)">
							{{v.name}}
						</view>
					</template>
					<view class="user_list_box red" @click="createUser">新建<uni-icons type="right" size="16" color="orangered"></uni-icons>
					</view>
				</view>
				<view class="check_users" v-for="(v,i) in tourist" :key="i">
					<text class="lef">{{v.title}}</text>
					<view class="blue" v-if="!v.users" @click="openFun(i)">点击选择游玩人信息</view>
					<view class="" v-else>
						<view class="title">
							姓名 {{v.users}}
						</view>
						<view class="">
							证件号 {{v.code}}
						</view>
						<view class="">
							手机号 {{v.phone}}
						</view>
					</view>
				</view>
			</view>
			<view class="module_box">
				<view class="title">
					促销优惠
				</view>
				<view class="preferential">
					<view class="">
						平台优惠券
					</view>
					<view class="preferents">
						可用0张
						<uni-icons type="right" size="16" color="gray" />
					</view>
				</view>
			</view>
			<view class="module_box">
				<view class="title">
					支付方式
				</view>
				<view class="pay_box">
					<view class="pay_title">
						微信支付
					</view>
					<view class="pay_text">
						方便快捷
					</view>
				</view>
			</view>
		</view>
		<view class="footer">
			<view class="left">
				合计
				<view class="price">
					￥
					<text>{{sumPrice}}</text>
				</view>
			</view>
			<view class="btn" @click="submitGoods" >
				结算
			</view>
		</view>



		<!-- 选择游客 常用联系人 -->
		<uni-popup ref="popup" type="bottom" @click="closeFun" background-color="#fff">
			<view class="popup_box" :class="{ 'popup-height': 'left' }">
				<view class="title">
					常用联系人
				</view>
				<view class="add_new">
					<uni-icons type="plusempty" color="orangered" size="16"></uni-icons>
					新增联系人
				</view>
				<view class="bodys">
					<template v-for="(v,i) in userList" :key="i">
						<view class="user_box">
							<uni-icons type="checkbox" size="30" @click="checkUsers(v)"></uni-icons>
							<view class="userBox" @click="checkUsers(v)">
								<view class="names">
									{{v.name}}
									<text v-if="v.isdefault==1">默认</text>
								</view>
								<view class="phones">
									证件号 {{v.idcard}}
								</view>
								<view class="phones">
									手机号 {{v.tel}}
								</view>
							</view>
							<uni-icons type="compose" color="orangered" size="30" @click="eidtUsers(v)"></uni-icons>

						</view>

					</template>
				</view>

			</view>
		</uni-popup>
		<!-- 新增联系人 -->
		<uni-popup ref="add" type="bottom" @click="closeAdd" background-color="#fff">
			<view class="popup_box" :class="{ 'popup-height': 'left' }">
				<view class="title">
					新增联系人
				</view>
				<AddConcat @success="addSuccessUser"></AddConcat>
			</view>
		</uni-popup>
		<!-- 编辑联系人 -->

	</view>
</template>

<script setup>
	import AddConcat from "./components/addConcat.vue"
	import {
		ref,
		reactive,
		onMounted,
		getCurrentInstance,
		computed
	} from "vue";
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		qsAll
	} from "@/utils/qsAll.js"
	import {
		shopDetails
	} from "@/api/index.js"
	import {
		getMemInfo
	} from "@/api/user.js"
	import {
		getCapchaRepeat,createOrder
	} from "@/api/order.js"

	// 选中id
	const ids = ref('')
	// 用户信息
	const userList = ref([])
	// 订单详情
	const details = ref({})
	const checkuserList = ref({})
	const num = ref(1)
	const goodsName =ref()
	const price =ref()
	// 游客列表
	const tourist = ref([{
		title: '游客1',
		users: '',
		code: '',
		phone: ''
	}])
	// 当日时间数组
	const timesList = reactive([])
	// 用户选中的出发游玩日期
	const checkTime = ref(null)
	const checkTimeFn = (v) => {
		checkTime.value = v.timer
		orderForm.gotime = v.timesSub
		orderForm.gotimer = v.timer
	}
	const sumPrice = computed(()=>{
		return price.value*100*orderForm.num/100
	})
	const popup = ref(null);
	const add = ref(null);
	const changes = ref(null);
	const skuID = ref()
	const orderForm = reactive({
		"skuid": null,
		"key": "",
		"num": 1,
		"gotime": "",
		"username": "",
		"tel": "",
		"idcard": "",
		"gotimer": null,
		"userList": []
	})
	const telList = reactive({
		"username": "",
		"tel": "",
		"idcard": ""
	})
	onLoad((options) => {
		ids.value = options.ids
		orderForm.skuid = options.skuID
		goodsName.value=options.goodsname
		price.value=options.price

	})
	const tid = ref()
	onShow(() => {
		console.log(ids.value, 'ids')
		createGoTimeArr()
		qsAll([shopDetails({
			id: ids.value
		}), getMemInfo(), getCapchaRepeat()]).then(res => {
			console.log(res, 'res')
			// 获取商品详情
			details.value = res[0].value.data
			tid.value = res[0].value.data.tid
			// 获取 联系人列表
			userList.value = res[1].value.data
			// 设置默认联系人
			let data = {},
				num = 0
			// 查找 有没有默认的 联系人
			userList.value.forEach((v, i) => {
				// return ? v
				if (v.isdefault == 1) {
					data = v
					num++
				}
			})
			//如果没有默认的联系人 设置 第一条数据 未 默认联系人 
			data = (num == 0 ? userList.value[0] : data)
			checkuserList.value = data

			orderForm.username = data.name
			orderForm.tel = data.tel
			orderForm.idcard = data.idcard

			// console.log(res[2], 302)
			orderForm.key = res[2].value.data
		})
	})
	// 选择游客
	const toChecktourist = (num, v) => {
		console.log(v, 286)
		userList.value[num].check = (userList.value[num].check == true ? false : true)
		// 判断购票数量 如果购票数量是1的话 就替换
		// 如果他是选中状态
		if (userList.value[num].check) {
			// 加入到游客列表里面  首先 需要判断数量 如果是一个人买 直接覆盖 如果是 >1 的 需要循环游客列表 判断身份证号是否存在 如果存在不允许添加 如果不存在 可以添加
			
				// 使用Array.prototype.some()方法检查游客列表中是否存在具有相同idcard的用户
				const exists = tourist.value.some(touristItem => touristItem.code === v.idcard);
				if (exists) {
				    // 如果找到了具有相同idcard的用户，显示错误提示
				    uni.showToast({
				        title: "当前用户已经存在",
				        icon: "fail"
				    });  
					userList.value[num].check =false
				}else{
					let flag =false
					// 如果没有相同用户 
					for(let i=0;i<tourist.value.length;i++){
						if(!tourist.value[i].users){
							// 如果有空值 直接赋值 
							tourist.value[i].users = v.name
							tourist.value[i].code = v.idcard
							tourist.value[i].phone = v.tel
							flag=true
							break
						}
					}
					// 如果数据 都不是空的 就修改最后一条
					if(!flag){
						let index = tourist.value.length-1
						// 获取一下 最后一条选中的数据 设置其选中效果 为未选中效果
						for(let i=0;i<userList.value.length;i++){
							if(userList.value[i].idcard===tourist.value[index].code){
								userList.value[i].check = false
							}
						}
						// 覆盖原有信息
						tourist.value[index].users = v.name
						tourist.value[index].code = v.idcard
						tourist.value[index].phone = v.tel
					}
					
				}
			
		}else{
			
				// 获取一下 最后一条选中的数据 设置其选中效果 为未选中效果
				for(let i=0;i<userList.value.length;i++){
					if(userList.value[i].idcard===v.idcard){
						userList.value[i].check = false
					}
				}
				// 循环选中列表 清空 这条数据
				for(let i=0;i<tourist.value.length;i++){
					if(tourist.value[i].code===v.idcard){
						tourist.value[i].users = ""
						tourist.value[i].code = ""
						tourist.value[i].phone = ""
					}
				}
			
		}
		orderForm.userList= []
		// 更新用列表信息
		for(let i=0;i<tourist.value.length;i++){
			orderForm.userList.push({
				"username": tourist.value[i].users,
				"tel": tourist.value[i].phone,
				"idcard": tourist.value[i].code
			})
		}
		
		console.log(orderForm,378)

	}
	// 添加游客
	const addTourist = () => {
		num.value++
		orderForm.num++
		tourist.value.push({
			title: '游客' + num.value,
			users: '',
			code: '',
			phone: ''
		})
	}
	// 减少游客
	const editTourist = () => {
		if (num.value > 1) {
			num.value--
			orderForm.num--
			tourist.value.splice(tourist.value.length - 1)
		}
	}
	const touristIndex = ref('')
	const openFun = ((num) => {
		touristIndex.value = num
		popup.value.open();
	})

	const closeFun = (() => {
		touristIndex.value = ''
		popup.value.close()
	})
	const closeAdd = (() => {
		add.value.close()
	})
	const closeChange = (() => {
		change.value.close()
	})

	const createGoTimeArr = () => {
		// 清空数组 timesList.splice(0, timesList.length);
		timesList.length = 0
		// 先判断当前时间  看几点 4点以后不让买票 16
		let currentTime = new Date();
		let currentDate = new Date();
		let hours = currentTime.getHours();
		let start = 0,
			end = 10
		if (hours >= 16) {
			console.log("当前时间大于或等于16:00");
			// 循环10次，每次增加一天
			start = 1;
			end = 11
		}
		for (let i = start; i < end; i++) {
			// 创建新的Date对象，表示当前日期加上i天
			let futureDate = new Date(currentDate.getTime() + i * 24 * 60 * 60 * 1000);

			// 获取年、月、日
			let year = futureDate.getFullYear();
			let month = futureDate.getMonth() + 1 > 9 ? futureDate.getMonth() + 1 : '0' + (futureDate.getMonth() +
			1); // getMonth()返回的月份是从0开始的
			let day = futureDate.getDate() > 9 ? futureDate.getDate() : '0' + futureDate.getDate();

			// 获取星期几
			let dayOfWeek = futureDate.getDay();
			let days = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
			let dayName = days[dayOfWeek];

			// 输出结果
			console.log(year + "年" + month + "月" + day + "日，" + dayName);
			timesList.push({
				times: month + "月" + day + "日",
				text: dayName,
				timer: futureDate.getTime(),
				timesSub:year+'-'+month+'-'+day
			})
		}
		console.log(timesList, 382)

	}
	
	
	const submitGoods = ()=>{
		console.log("zoule")
		createOrder(orderForm).then(e=>{
			console.log(e,452)
			/**
			 * ！！！！注意： 支付成功或者失败之后的提示 不重要 ，重要的是 不管成功和失败
			 * 都需要跳转到 支付成功的提示页面，在这个页面中 需要传一个订单号，根据订单号
			 * 查询数据库的支付状态，来确定用户是否支付完成！
			 */
			// #ifdef MP-WEIXIN
			// 发起支付
			uni.requestPayment({
			    "provider": "wxpay",
			    "orderInfo": {
			        "appid": e.data.appid,  // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
			        "noncestr": e.data.noncestr, // 随机字符串
			        "package": e.data.package,        // 固定值
			        "partnerid": e.data.partnerid,      // 微信支付商户号
			        "prepayid": e.data.prepayid, // 统一下单订单号
			        "timestamp": e.data.timestamp,        // 时间戳（单位：秒）
			        "sign": e.data.sign // 签名，这里用的 MD5/RSA 签名
			    },
			    success(res) {
					console.log(res)
				
				},
			    fail(e) {
					console.log(e)
				},
				complete(){
					uni.reLaunch({
						url:"/pagesC/oders/oders"
					})
				}
			})
			// #endif
			// #ifndef MP-WEIXIN
			uni.showToast({
				title: "订单已经生成",
				icon:"none",
				duration: 2000,
				success() {
					uni.navigateTo({
						url:"/pagesC/lineOder/lineOder?tid="+tid.value
					})
				}
			});
			
			// #endif
		})
	}
	
	const riFlag = ref(false)
	// 点击联系人的内阁小日历
	function openSelUser(){
		console.log("点击")
		riFlag.value = true
		popup.value.open();
	}
	// 点击联系人列表
	function checkUsers(item){
		console.log(item,496)
		if(riFlag.value){
			checkuserList.value = item
			// 点击了小日历
			popup.value.close()
			riFlag.value=false
		}else{
			console.log(tourist.value,touristIndex.value,item,506)
			toChecktourist(touristIndex.value,item)
			popup.value.close()
		}
		
	}
	
	const createUserFlag = ref(false)
	// 点击新建
	function createUser(){
		createUserFlag.value=true
		add.value.open();
	}
	
	function addSuccessUser(flag){
		if(flag){
			// 添加成功 ，更新用户列表 关闭弹框
			getMemInfo().then(res => {
				console.log(res, 'res')
				
				// 获取 联系人列表
				userList.value = res.data
				// 设置默认联系人
				let data = {},
					num = 0
				// 查找 有没有默认的 联系人
				userList.value.forEach((v, i) => {
					// return ? v
					if (v.isdefault == 1) {
						data = v
						num++
					}
				})
				createUserFlag.value=false
				add.value.close();
			})
			
		}
	}
	
</script>

<style lang="less" scoped>
	.container {
		display: flex;
		flex-direction: column;
		overflow-x: hidden;

		.body {
			flex: 1;
			padding: 0 20rpx;
			padding-bottom: 20rpx;
			box-sizing: border-box;
			overflow-y: auto;
		}

		.module_box {
			margin-top: 20rpx;
			padding: 30rpx 0;
			box-sizing: border-box;
			border-radius: 16rpx;
			background: #fff;

			.title {
				font-weight: 600;
				padding: 0 30rpx;
				padding-bottom: 20rpx;
				box-sizing: border-box;
				display: flex;
				justify-content: space-between;
			}

			.moduletitle {
				padding: 0 30rpx;
				padding-bottom: 30rpx;
				font-weight: 600;
				box-sizing: border-box;
				border-bottom: 1rpx solid lightgray;
			}

			.time_box {
				padding: 30rpx;
				box-sizing: border-box;
				border-bottom: 1rpx solid lightgray;

				.titles {
					padding: 20rpx 0;
					font-weight: 600;
				}


				.times_box {
					width: 100%;
					display: flex;
					overflow-x: auto;
					white-space: nowrap;
					font-size: 24rpx;

					.timesBox {
						border: 1rpx solid orangered;
						// float: left;
						border-radius: 10rpx;
						padding: 20rpx 10rpx;
						display: inline-block;
						width: 200rpx;

						view {
							text-align: center;

						}

						view+view {
							padding-top: 6rpx;
						}
					}

					.timesBox+.timesBox {
						margin-left: 20rpx;
					}
				}
			}

			.price_box {
				padding: 30rpx;
				box-sizing: border-box;
				display: flex;
				justify-content: space-between;

				.price_text {
					font-size: 30rpx;

					.titles {
						font-weight: 600;
						font-size: 34rpx;
						padding-bottom: 15rpx;
					}
				}

				.price_number {
					display: flex;
					align-items: center;

					.num {
						text-align: center;
						width: 66rpx;
						font-weight: 600;
						font-size: 36rpx;
					}

					.btn {
						border-radius: 50%;
						border: 4rpx solid gray;
						box-sizing: border-box;
						color: gray;
						width: 60rpx;
						height: 60rpx;
						text-align: center;
						line-height: 50rpx;
						font-size: 60rpx;
					}

					.checks {
						color: orangered;
						border-color: orangered;
					}
				}
			}

			.user_list {
				display: flex;
				flex-wrap: wrap;
				padding: 20rpx 30rpx;
				box-sizing: border-box;
				font-size: 24rpx;
				.user_list_box {
					border-radius: 20rpx;
					// padding: 30rpx 40rpx;
					line-height: 80rpx;
					width: 130rpx;
					text-align: center;
					border: 1rpx solid orangered;
					margin: 10rpx;
				}

				.red {
					color: orangered;
				}

				.user_list_box+.user_list_box {
					margin-left: 20rpx;
				}


			}

			.check_pheuser {
				background: orangered;
				color: #fff;
			}

			.check_users {
				// background: orangered;
				// color: #fff;
				display: flex;
				padding: 20rpx 30rpx;
				box-sizing: border-box;

				.lef {
					margin-right: 20rpx;
				}

				.blue {

					color: #527aff;
				}
			}

			.preferential {
				padding: 20rpx 30rpx;
				box-sizing: border-box;
				display: flex;
				justify-content: space-between;

				.preferents {
					color: orangered;
				}
			}

			.user_box {}

			.pay_box {
				border-radius: 16rpx;
				border: 1rpx solid orangered;
				background: #f9eeec;
				margin-left: 30rpx;
				width: 260rpx;
				padding: 30rpx 20rpx;
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				justify-content: center;

				.pay_title {
					font-weight: 600;
					margin-bottom: 10rpx;
					font-size: 30rpx;
				}

				.pay_text {
					font-size: 28rpx;
				}
			}

		}

		.footer {
			width: 100%;
			height: 140rpx;
			background: #fff;
			padding: 0 20rpx;
			box-sizing: border-box;
			border-top: 1rpx solid lightgray;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.left {
				display: flex;
				align-items: center;
			}

			.price {
				color: orangered;
				font-size: 20rpx;
				font-weight: 600;

				text {
					font-size: 42rpx;
				}
			}

			.btn {
				width: 200rpx;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				border-radius: 80rpx;
				background: orangered;
				color: #fff;
			}
		}

	}

	.uni-popup {
		width: 100%;
		height: 100%;
	}

	.uni-popup .uni-popup__wrapper .popup_box {
		height: 60vh;
		// overflow: auto;
		display: flex;
		flex-direction: column;
		position: fixed;
		bottom: 0;
		left: 0;
		box-sizing: border-box;
		// margin-top: 50vh;
		border-radius: 20rpx 20rpx 0 0;
		width: 100%;
		background: #f8f8f8;

		.title {
			text-align: center;
			padding: 10rpx 0;
		}

		.add_new {
			width: 90%;
			margin-left: 5%;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			box-sizing: border-box;
			color: orangered;
			background: #f9eeec;
			border: 1rpx solid orangered;
			border-radius: 80rpx;
		}

		.bodys {
			width: 100%;
			padding: 0 5%;
			padding-bottom: 30rpx;
			box-sizing: border-box;
			flex: 1;
			overflow-y: auto;

			.user_box {
				width: 100%;
				padding: 30rpx;
				box-sizing: border-box;
				background-color: #fff;
				border-radius: 16rpx;
				margin-top: 20rpx;
				display: flex;
				align-items: center;

				.userBox {
					flex: 1;
					padding: 0 10rpx;

					.names {
						font-weight: 600;
						font-size: 36rpx;

						text {
							font-size: 26rpx;
							color: orangered;
							font-weight: 400;
							background: #f9eeec;
							margin-left: 10rpx;
							padding: 6rpx 10rpx;
							border-radius: 6rpx;
							border: 1rpx solid orangered;
						}
					}

					.phones {
						color: gray;
						font-size: 30rpx;
						margin-top: 10rpx;
					}

				}
			}

		}

	}

	.checkTime {
		background-color: orangered;
		color: #fff;
	}
</style>